import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

public class Chapter01 {
    private static final int ONE_WEEK_IN_SECONDS = 7 * 86400;
    private static final int VOTE_SCORE = 432;
    private static final int ARTICLES_PER_PAGE = 25;
    public static void main(String[] args) {
        new Chapter01().run();
    }

    private void run() {
        Jedis jedis = new Jedis("192.168.179.21", 6379);
        jedis.select(15);

        String articleId = postArticle(
                jedis, "皇子", "我将带头冲锋", "http://www.google.com");
        System.out.println("We posted a new article with id: " + articleId);
        System.out.println("Its HASH looks like:");
        Map<String, String> articleData = jedis.hgetAll("article:" + articleId);
        for (Map.Entry<String,String> entry :articleData.entrySet()){
            System.out.println(" "+entry.getKey()+": "+entry.getValue());
        }

        System.out.println();


        articleVote(jedis, "other_user", "article:" + articleId);
        
    }

    /**
     * 投票功能的实现
     * @param jedis
     * @param otherUser
     * @param article
     */
    private void articleVote(Jedis jedis, String otherUser, String article) {
        //计算文章投票的截止时间
        long cutoff = (System.currentTimeMillis() / 1000) - ONE_WEEK_IN_SECONDS;
        //检查是否还可以对文章进行投票
        if (jedis.zscore("time:",article) < cutoff){
            return;
        }
        //取出文章id
        String articleId =article.substring(article.indexOf(":") + 1);
        //如果用户是第一次为这篇文章投票，那么增加这篇文章的投票数量和评分
        if (jedis.sadd("voted:"+articleId,otherUser) ==1){
            jedis.zincrby("score:",VOTE_SCORE,article);
            jedis.hincrBy(article,"votes",1);
        }

    }

    /**
     * 发布文章
     * @param jedis  redis 连接
     * @param username 名称
     * @param title 标题
     * @param link 文章链接
     * @return
     */
    private String postArticle(Jedis jedis, String username, String title, String link) {
        //生成一个新的文章ID  自增id
        String articleId = String.valueOf(jedis.incr("article:"));
        //将发布文章的用户添加到文章的已投票用户名单里面，然后将这个名单的过期时间设置为一周
        String voted = "voted:" + articleId;
        jedis.sadd(voted, username);
        jedis.expire(voted, ONE_WEEK_IN_SECONDS);
        long now = System.currentTimeMillis() / 1000;
        //将文章信息存储到一个散列里面
        String article = "article:" + articleId;
        HashMap<String,String> articleData = new HashMap<String,String>();
        articleData.put("title", title);
        articleData.put("link", link);
        articleData.put("user", username);
        articleData.put("now", String.valueOf(now));
        articleData.put("votes", "1");
        jedis.hmset(article, articleData);
        //1：存储成员的文章id 分值为文章和发布时间
        jedis.zadd("score:", now + VOTE_SCORE, article);
        //2：存储成员的文章id 分值为文章的评分
        jedis.zadd("time:", now, article);
        return articleId;
    }
}
